package com.leo.chapter07;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;

/**
 * 支持关闭的日志服务
 * @author xuexiaolei
 * @version 2017年10月16日
 */
public class LogService {
    private final BlockingQueue<String> queue;
    private final LoggerThread logger;
    private final PrintWriter writer;
    private boolean isShutDown;
    private int reservations;

    public LogService(BlockingQueue<String> queue, PrintWriter writer) {
        this.queue = queue;
        this.writer = writer;
        this.logger = new LoggerThread(writer);
    }

    public void start() { logger.start(); }

    public void stop(){
        synchronized (this){ isShutDown = true; }
        logger.interrupt();
    }

    public void log(String msg) throws InterruptedException{
        synchronized (this){
            if (isShutDown) throw new IllegalStateException("服务都关闭了，别来了");
            ++reservations;
        }
        queue.put(msg);
    }

    //真正干活的线程
    private class LoggerThread extends Thread{
        private final PrintWriter writer;
        private LoggerThread(PrintWriter writer) {
            this.writer = writer;
        }

        public void run(){
            try {
                while (true){
                    try {
                        synchronized (LogService.this){
                            if (isShutDown && reservations==0) break;
                        }
                        String msg = queue.take();
                        synchronized (LogService.this){ --reservations; }
                        writer.print(msg);
                    } catch (InterruptedException e) {
                        /* 重试 */
                    }
                }
            } finally {
                writer.close();
            }
        }
    }
}
